﻿using DevExpress.XtraEditors;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WinForm_Mes.WorkingManagement.TeamType
{
    public partial class UpdateTeamTypeForm : DevExpress.XtraEditors.XtraForm
    {
        private HttpClient httpClient;
        private string baseUrl = "http://localhost:5053";
        private TeamTypeItem teamTypeItem;

        public UpdateTeamTypeForm(TeamTypeItem selectedItem)
        {
            InitializeComponent();
            InitializeHttpClient();
            this.teamTypeItem = selectedItem;
        }

        private void InitializeHttpClient()
        {
            httpClient = new HttpClient();
            httpClient.BaseAddress = new Uri(baseUrl);
            httpClient.DefaultRequestHeaders.Accept.Clear();
            httpClient.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
        }

        private void UpdateTeamTypeForm_Load(object sender, EventArgs e)
        {
            // 数据反显
            if (teamTypeItem != null)
            {
                textEdit1.Text = teamTypeItem.teamTypeCode;
                textEdit2.Text = teamTypeItem.teamTypeName;
                textEdit3.Text = teamTypeItem.createUser;

                // 如果有日期，则转换并显示
                if (!string.IsNullOrEmpty(teamTypeItem.createTime))
                {
                    try
                    {
                        DateTime createDate = DateTime.Parse(teamTypeItem.createTime);
                        dateEdit1.EditValue = createDate;
                    }
                    catch { /* 日期格式错误时不处理 */ }
                }

                memoEdit1.Text = teamTypeItem.remark;

                // 由于是修改，编码通常不允许修改
                textEdit1.ReadOnly = true;
            }
        }

        private async void btnUpdate_Click(object sender, EventArgs e)
        {
            // 验证输入
            if (string.IsNullOrEmpty(textEdit2.Text))
            {
                XtraMessageBox.Show("请输入班组类型名称", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            try
            {
                // 构建请求数据
                var updateData = new
                {
                    id = teamTypeItem.id,
                    teamTypeCode = textEdit1.Text.Trim(),
                    teamTypeName = textEdit2.Text.Trim(),
                    createUser = textEdit3.Text.Trim(),
                    createTime = dateEdit1.EditValue != null ? Convert.ToDateTime(dateEdit1.EditValue).ToString("yyyy-MM-dd") : "",
                    remark = memoEdit1.Text?.Trim()
                };

                // 序列化为JSON
                string jsonContent = JsonConvert.SerializeObject(updateData);
                HttpContent content = new StringContent(jsonContent, Encoding.UTF8, "application/json");

                // 发送PUT请求
                HttpResponseMessage response = await httpClient.PostAsync("/api/Scheduling/UpdateTeamType", content);

                if (response.IsSuccessStatusCode)
                {
                    string responseData = await response.Content.ReadAsStringAsync();
                    var result = JsonConvert.DeserializeObject<BaseResponse>(responseData);

                    if (result.code == 200)
                    {
                        XtraMessageBox.Show("修改成功", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        DialogResult = DialogResult.OK; // 设置对话框结果为OK，触发父窗体刷新
                        Close(); // 关闭窗体
                    }
                    else
                    {
                        XtraMessageBox.Show($"修改失败：{result.message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
                else
                {
                    XtraMessageBox.Show($"请求失败：{response.StatusCode}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show($"发生异常：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            DialogResult = DialogResult.Cancel;
            Close();
        }

        
    }
}